﻿using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Device;
using ManagementApi.Models.System.ProjectCheckinDeviceCommandLog;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Device;
using Modules.Device.Entitys;
using Modules.Person;
using Modules.Project;
using Modules.Project.Entitys;
using PmSoft;
using PmSoft.Exceptions;
using PmSoft.Utilities;
using static Modules.Device.CheckInDeviceConstants;

namespace ManagementApi.Controllers.ManagerPannel
{
    /// <summary>
    /// 项目考勤机设备管理
    /// </summary>
    [Route("/api/v1/manager/checkindevice")]
    [ApiController]
    [Authorize(Roles = "Manager")]
    public class CheckInDeviceController : ControllerBase
    {
        private readonly CheckinDeviceService checkinDeviceService;
        private readonly CheckinDeviceCommandService projectCheckinDeviceCommandService;
        private readonly ProjectManagerApplicationContext applicationContext;
        private readonly ProjectGroupMemberService projectGroupMemberService;
        private readonly PersonService personService;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        /// <summary>
        /// </summary>
        /// <param name="applicationContext"></param>
        /// <param name="checkinDeviceService"></param>
        /// <param name="projectCheckinDeviceCommandService"></param>
        /// <param name="projectGroupMemberService"></param>
        /// <param name="personService"></param>
        /// <param name="ownAuthorizer"></param>
        public CheckInDeviceController(ProjectManagerApplicationContext applicationContext, CheckinDeviceService checkinDeviceService, CheckinDeviceCommandService projectCheckinDeviceCommandService, ProjectGroupMemberService projectGroupMemberService, PersonService personService, ProjectOwnAuthorizer ownAuthorizer)
        {
            this.applicationContext = applicationContext;
            this.checkinDeviceService = checkinDeviceService;
            this.projectCheckinDeviceCommandService = projectCheckinDeviceCommandService;
            this.projectGroupMemberService = projectGroupMemberService;
            this.personService = personService;
            this.ownAuthorizer = ownAuthorizer;
        }

        /// <summary>
        /// 获取考勤机信息列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<CheckInDeviceDto>> GetProjectCheckInDevices([FromQuery] CheckInDeviceQuery query, int pageNum = 1, int pageSize = 20)
        {
            if (!query.ProjectId.HasValue)
            {
                query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            }
            var devices = checkinDeviceService.GetProjectCheckinDevices(query, pageNum, pageSize);
            var dtos = devices.AsPageDto(source => { return source.AsDto(applicationContext); });
            return ApiResult<PageDto<CheckInDeviceDto>>.Success(dtos);
        }

        /// <summary>
        /// 考勤机信息表单数据
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<CheckInDeviceEditForm> GetRole(int id)
        {
            var device = checkinDeviceService.GetProjectCheckinDevice(id);
            if (device == null)
                return ApiResult<CheckInDeviceEditForm>.Failure("考勤机信息数据不存在");
            return ApiResult<CheckInDeviceEditForm>.Success(device.AsForm());
        }

        /// <summary>
        /// 批量下发命令
        /// </summary>
        /// <param name="ids">设备id</param>
        /// <param name="codes">命令编码</param>
        /// <returns></returns>
        [HttpPost("issuecommand")]
        public async Task<ApiResult> IssueCommand(string ids, string codes)
        {
            //string host = $"{HttpContext.Request.Host.Host}:{HttpContext.Request.Host.Port}";
            if (string.IsNullOrEmpty(ids)) return ApiResult.Failure("设备不能为空");
            if (string.IsNullOrEmpty(codes)) return ApiResult.Failure("请选择要下发的命令");
            var deviceIds = ValueUtility.ConvertToList<int>(ids);
            var commandCodes = ValueUtility.ConvertToList<考勤机命令>(codes);
            IEnumerable<CheckinDevice> devices = checkinDeviceService.GetProjectCheckinDevices(deviceIds);
            //数据权限验证
            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(devices.Select(i => i.ProjectId));
            foreach (var device in devices)
            {
                foreach (var commandType in commandCodes)
                {
                    CheckinDeviceCommand command = new()
                    {
                        Name = commandType.GetDescription(),
                        Code = commandType,
                        MessageId = Guid.NewGuid().ToString(),
                        DeviceCode = device.Code,
                        Status = 命令下发状态.待下发,
                        IsAuto = false
                    };
                     projectCheckinDeviceCommandService.Send(command, device);
                }
            }
            return ApiResult.Success("下发成功");
        }

        /// <summary>
        /// 获取考勤机下发记录列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("log_page")]
        public ApiResult<PageDto<ProjectCheckinDeviceCommandDto>> GetProjectCheckInDeviceCommands([FromQuery] CheckinDeviceCommandQuery query, int pageNum = 1, int pageSize = 20)
        {
            var devices = projectCheckinDeviceCommandService.GetProjectCheckinDeviceCommands(query, pageNum, pageSize);
            List<int> deviceIds = devices.Select(a => a.Id).ToList();
            var dtos = devices.AsPageDto(source => { return source.AsDto(); });
            return ApiResult<PageDto<ProjectCheckinDeviceCommandDto>>.Success(dtos);
        }

        /// <summary>
        /// 单个人员下发命令
        /// </summary>
        /// <param name="memberId">班组成员id</param>
        /// <param name="type">类型：1新增 0 删除</param>
        /// <returns></returns>
        [HttpPut("send_person/{memberId}/{type}")]
        public ApiResult SendCommand(int memberId, int type)
        {
            #region 下发人员信息到设备

            ProjectGroupMember projectGroupMember = projectGroupMemberService.GetMember(memberId) ?? throw new BusinessException("人员不存在");
            //数据权限验证
            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(projectGroupMember.ProjectId);

            var person = personService.GetPerson(projectGroupMember.PersonId) ?? throw new BusinessException("人员不存在");
            IEnumerable<CheckinDevice> devices = checkinDeviceService.GetProjectCheckinDevicesByProjectId(applicationContext.CurrentProjectInfo.ProjectId);
            foreach (var device in devices)
            {
                CheckinDeviceCommand log = new()
                {
                    Name = 考勤机命令.人员进场后下发.GetDescription(),
                    Code = 考勤机命令.人员进场后下发,
                    MessageId = Guid.NewGuid().ToString(),
                    DeviceCode = device.Code,
                    Status = 命令下发状态.待下发,
                    IsAuto = false
                };
                if (type == 1)
                {
                    log.Name = 考勤机命令.人员进场后下发.GetDescription();
                    log.Code = 考勤机命令.人员进场后下发;
                }
                else if (type == 0)
                {
                    log.Name = 考勤机命令.人员离场后下发.GetDescription();
                    log.Code = 考勤机命令.人员离场后下发;
                }
                projectCheckinDeviceCommandService.Send(log, device, new List<PersonInfo>() { person });
            }

            #endregion 下发人员信息到设备

            return ApiResult.Success("命令下发成功");
        }
    }
}